package com.elite.groovy.controller;

import cn.hutool.http.HtmlUtil;
import com.elite.groovy.kh.KHDBConfig;
import com.elite.groovy.kh.KHUtil;
import com.elite.groovy.service.ProcessServiceRequire;
import com.elite.groovy.util.EliteBean;
import com.record.ccod.CCODUtils;
import com.record.ccod.CCODUtils_WaRTC;
import com.record.shdx.SHDXRecUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Administrator
 */
@Slf4j
@Controller
@ResponseBody
public class ScriptController {

    @Autowired
    private ProcessServiceRequire processServiceRequire;

    @Autowired
    private EliteBean eliteBean;

    /**
     * 调用类路径下的groovy脚本
     *
     * @param groovyName
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/GeneralService/{groovyName}")
    @CrossOrigin
    public void getOneQuestionService(@PathVariable String groovyName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        StopWatch stopWatch = new StopWatch();
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        log.debug("====================================Execute Script [{}] Start======================================================", groovyName);
        PrintWriter out = response.getWriter();
        try {
            stopWatch.start();
            processServiceRequire.doOldGeneralService(groovyName, request, response);
        } catch (FileNotFoundException e) {
            groovyName = HtmlUtil.filter(groovyName);
            out.print(groovyName + " Groovy Script Not Found");
        } catch (Exception e) {
            log.error("", e);
            out.print(e.getMessage());
        } finally {
            stopWatch.stop();
            log.debug("Execute Script: [{}] End. And Spend: [{}] ms", groovyName, stopWatch.getTotalTimeMillis());
            log.debug("=====================================Execute Script [{}] End========================================================", groovyName);
        }
    }

    /**
     * 调用数据库中的groovy脚本
     *
     * @param groovyName
     * @param request
     * @param response
     * @throws IOException
     */
    @CrossOrigin
    @RequestMapping("/call/{groovyName}")
    public void invokeByName(@PathVariable String groovyName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        log.debug("====================================Execute DB Script [{}] Start======================================================", groovyName);
        PrintWriter out = response.getWriter();
        try {
            Map<String, Object> groovyMap = eliteBean.getGroovyScriptByDB(groovyName);
            if (groovyMap == null) {
                groovyName = HtmlUtil.filter(groovyName);
                out.print(groovyName + " Groovy Script Not Found");
                return;
            }
            String groovyContent = groovyMap.get("GROOVY_CONTENT").toString();
            Timestamp modifiedDate = (Timestamp) groovyMap.get("MODIFIED_TIME");
            long modifiedDateLong = modifiedDate.getTime();
            processServiceRequire.doDbGroovyScriptService(groovyName, groovyContent, modifiedDateLong, request, response);
        } catch (Exception e) {
            log.error("", e);
            out.print(e.getMessage());
        } finally {
            stopWatch.stop();
            log.debug("Execute DB Script: [{}] End. And Spend: [{}] ms", groovyName, stopWatch.getTotalTimeMillis());
            log.debug("=====================================Execute DB Script [{}] End========================================================", groovyName);

        }
    }

    /**
     * 调用数据库中的groovy脚本
     *
     * @param groovyName
     * @param request
     * @param response
     * @throws IOException
     */
    @CrossOrigin
    @RequestMapping("/api/{groovyName}")
    public void apiByName(@PathVariable String groovyName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        log.debug("====================================Execute DB Script [{}] Start======================================================", groovyName);
        PrintWriter out = response.getWriter();
        try {
            Map<String, Object> groovyMap = eliteBean.getGroovyScriptByDB(groovyName);
            if (groovyMap == null) {
                groovyName = HtmlUtil.filter(groovyName);
                out.print(groovyName + " Groovy Script Not Found");
                return;
            }
            String groovyContent = groovyMap.get("GROOVY_CONTENT").toString();
            Timestamp modifiedDate = (Timestamp) groovyMap.get("MODIFIED_TIME");
            long modifiedDateLong = modifiedDate.getTime();
            processServiceRequire.doDbGroovyScriptService(groovyName, groovyContent, modifiedDateLong, request, response);
        } catch (Exception e) {
            log.error("", e);
            out.print(e.getMessage());
        } finally {
            stopWatch.stop();
            log.debug("Execute DB Script: [{}] End. And Spend: [{}] ms", groovyName, stopWatch.getTotalTimeMillis());
            log.debug("=====================================Execute DB Script [{}] End========================================================", groovyName);

        }
    }

    /**
     * 系统录音获取
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @CrossOrigin
    @RequestMapping("/rec/getrec")
    public void recByName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        String rec_Res = "";
        log.debug("====================================Execute 系统录音获取 Start======================================================");
        try {

            String recData = request.getParameter("recdata");
            String multimode = request.getParameter("multimode"); // 空 需转码->文件流 无需转码->重定向 0原始Json 1封装XML返回
            log.debug("-系统录音获取 原始Get请求参数recdata:" + recData + " multimode:" + multimode);

            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            JSONObject REC_CFG_Main = JSONObject.fromObject(KHDBConfig.getParamConfig(jt, "REC_CFG_Main", "{\"1909090002\":\"doCCODRecord\",\"2209080002\":\"doCCODQuery\",\"2112200001\":\"doSHDXRecord\",\"1912110002\":\"doSHDXRecord\"}"));

            // 遍历基本信息
            String entId = "";
            String entId_type = "";
            Iterator iterator = REC_CFG_Main.keys();
            while (iterator.hasNext()) {
                entId = (String) iterator.next();

                if (recData.contains(entId + "|") || recData.contains(entId + ":")) {
                    entId_type = KHUtil.GetSFJV(REC_CFG_Main, entId);
                    break;
                }
            }

            // 如果未配置录音或未识别到EntID对应的录音则采用默认值
            if (KHUtil.isNull(entId_type)) {
                entId = "1909090002";
                entId_type = "doCCODQuery";
                log.warn("-系统录音获取 未配置或未识别出录音平台,使用默认值 EntID_type:" + entId_type);
            }

            if (entId_type.equalsIgnoreCase("doCCODRecord")) { // CCOD
                rec_Res = CCODUtils.doCCODRecord(jt, response, entId, recData, multimode);
            } else if (entId_type.equalsIgnoreCase("doCCODQuery")) { // CCOD 无控件
                rec_Res = CCODUtils_WaRTC.doCCODQuery(jt, response, "queryRecord", entId, recData, "", "", "", multimode); // query呼叫明细数据 queryRecord录音数据
            } else if (entId_type.equalsIgnoreCase("doSHDXRecord")) { // SHDX-1
                rec_Res = SHDXRecUtils.doSHDXRecord(jt, response, entId, recData, multimode);
            } else if (entId_type.equalsIgnoreCase("doSHDXRecord2")) { // SHDX-2
                rec_Res = SHDXRecUtils.doSHDXRecord2(jt, response, entId, recData, multimode);
            } else {
                rec_Res = "无法识别判断录音平台类型";
            }
            log.debug("-系统录音获取 API调用结果:" + rec_Res);

            // 如果非重定向或返回录音流则返回
            if (!KHUtil.isNull(rec_Res)) {
                response.setContentType("application/json;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                PrintWriter out = response.getWriter();

                out.print(rec_Res);

            }

        } catch (Exception e) {
            PrintWriter out = response.getWriter();
            out.print("系统录音获取 Exception异常" + e.getMessage());
            log.error("-系统录音获取 Exception异常", e);

        } finally {
            stopWatch.stop();
            log.debug("-系统录音获取 End. And Spend: [{}] ms", stopWatch.getTotalTimeMillis());
            log.debug("====================================Execute 系统录音获取 End======================================================");

        }
    }
}
